part of login;

class RegisterPanel extends StatefulWidget {
  const RegisterPanel({Key? key}) : super(key: key);

  @override
  _RegisterPanelState createState() => _RegisterPanelState();
}

class _RegisterPanelState extends State<RegisterPanel> {
  final FocusNode _usernameFocusNode = FocusNode();
  final FocusNode _passwordFocusNode = FocusNode();
  final FocusNode _verifyFocusNode = FocusNode();

  String username = '';
  String verifyCode = '';
  String password = '';

  bool btnEnabled = true;
  bool _isSubmitting = false;
  int counterSeconds = 0;
  late Timer counter;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void _onCounter(Timer timer) {
    if (timer.tick >= 60) {
      counter.cancel();
    }
    if (!mounted) return;
    setState(() {
      counterSeconds = math.max(0, 60 - timer.tick);
      if (counterSeconds <= 0) btnEnabled = true;
    });
  }

  _sendVerify() async {
    if (!btnEnabled) return;
    if (username.isEmpty) {
      toast('请填写手机号码', 2, 'top');
      _usernameFocusNode.requestFocus();
      return;
    }
    String captcha = '';
    await MyDialog.of(context).alert(
      CaptchaDialog(onChanged: (newValue) {
        captcha = newValue;
      }),
      buttonText: '确定',
    );
    if (captcha.isEmpty) return;

    btnEnabled = false;
    counter = Timer.periodic(const Duration(seconds: 1), _onCounter);
    final result = await app.login.sendSMS(username, captcha, 'register');

    if (result.code == 1) {
      toast('验证码发送成功', 2, 'top');
    } else {
      //counter.cancel();
      toast(result.message, 2, 'top');
    }
  }

  _doRegister() async {
    if (username.isEmpty) {
      toast('请填写手机号码', 2, 'top');
      return;
    }
    if (verifyCode.isEmpty) {
      toast('请填写验证码', 2, 'top');
      return;
    }
    if (password.isEmpty) {
      toast('请填写密码', 2, 'top');
      return;
    }
    //app.log.d([username, password]);
    _usernameFocusNode.unfocus();
    _passwordFocusNode.unfocus();
    _verifyFocusNode.unfocus();

    setState(() {
      _isSubmitting = true;
    });

    Result result = await app.login.doRegister({
      'mobile': username,
      'username': "u$username",
      'password': password,
      'repassword': password,
      'mobilecheck': verifyCode
    });
    if (result.code == 1) {
      toast('注册成功');
      if (result.data?['token'] != null) {
        app.login.setLogin(result.data);
        Navigator.pop(context);
      } else {
        _IndexPageState.of(context).changePanel('login');
      }
    } else {
      toast(result.message, 2, 'top');
    }

    setState(() {
      _isSubmitting = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        const SizedBox(height: 10),
        TextField(
            maxLength: 30,
            focusNode: _usernameFocusNode,
            cursorColor: Colors.white,
            style: const TextStyle(color: Colors.white, height: 1.5),
            strutStyle: const StrutStyle(height: 1.5, fontSize: 16.0),
            textAlignVertical: TextAlignVertical.center,
            decoration: LoginTheme.inputDecoration('手机号码', icon: Icons.person),
            onChanged: (String value) {
              username = value;
            }),
        const SizedBox(height: 20),
        TextField(
          maxLength: 6,
          focusNode: _verifyFocusNode,
          style: const TextStyle(color: Colors.white, height: 1.5),
          strutStyle: const StrutStyle(height: 1.5, fontSize: 16.0),
          textAlignVertical: TextAlignVertical.center,
          keyboardType: const TextInputType.numberWithOptions(),
          onChanged: (String value) {
            verifyCode = value;
          },
          decoration: LoginTheme.inputDecoration('验证码',
              icon: Icons.check_circle,
              action: Padding(
                padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 0),
                child: ElevatedButton(
                  onPressed: counterSeconds > 0 ? null : _sendVerify,
                  style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.white54),
                  ),
                  child: Text(
                    '发送' + (btnEnabled ? '' : "($counterSeconds)"),
                    style: const TextStyle(color: Colors.black54),
                  ),
                ),
              )),
        ),
        const SizedBox(height: 20),
        TextField(
          maxLength: 30,
          focusNode: _passwordFocusNode,
          style: const TextStyle(color: Colors.white, height: 1.5),
          strutStyle: const StrutStyle(height: 1.5, fontSize: 16.0),
          textAlignVertical: TextAlignVertical.center,
          obscureText: true,
          onChanged: (String value) {
            password = value;
          },
          decoration: LoginTheme.inputDecoration('登录密码', icon: Icons.lock),
        ),
        const SizedBox(height: 20),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: StateButton(
            onPressed: _doRegister,
            text: '注册',
            isLoading: _isSubmitting,
          ),
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 10),
          child: Row(
            children: <Widget>[
              const Spacer(),
              TextButton(
                onPressed: () {
                  _IndexPageState.of(context).changePanel('login');
                },
                child: Text('返回登录', style: LoginTheme.linkStyle),
              ),
            ],
          ),
        )
      ],
    );
  }
}
